package com.idp.app.excel;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.idp.app.dto.SyAjxxDto;
import com.idp.app.entity.SyAjxxEntity;
import com.idp.app.mapper.SyAjxxMapper;

import java.util.Date;
import java.util.List;
import java.util.Objects;

public class SyAjxxImportListener implements ReadListener<SyAjxxExcelDto> {

    private static final int BATCH_COUNT = 100;

    private List<SyAjxxExcelDto> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private SyAjxxMapper syAjxxMapper;

    public SyAjxxImportListener(SyAjxxMapper syAjxxMapper) {
        this.syAjxxMapper = syAjxxMapper;
    }


    @Override
    public void invoke(SyAjxxExcelDto syAjxxExcelDto, AnalysisContext analysisContext) {
        cachedDataList.add(syAjxxExcelDto);
        if (cachedDataList.size() >= BATCH_COUNT) {
            this.saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        this.saveData();
    }

    private void saveData() {

        if (CollectionUtil.isNotEmpty(cachedDataList)) {
            for (SyAjxxExcelDto syAjxxExcelDto : cachedDataList) {
                SyAjxxEntity syAjxx = BeanUtil.toBean(syAjxxExcelDto, SyAjxxEntity.class);
                if (!Objects.isNull(syAjxx.getId())) {
                    SyAjxxDto byId = syAjxxMapper.getById(syAjxx.getId());
                    if (byId != null) {
                        syAjxx.setUpdateTime(new Date());
                        syAjxx.setUpdateUser("admin");
                        syAjxx.setCreateUser("admin");
                        syAjxxMapper.updateById(syAjxx);
                    } else {
                        syAjxx.setId(IdUtil.simpleUUID());
                        syAjxx.setUpdateTime(new Date());
                        syAjxx.setUpdateUser("admin");
                        syAjxx.setCreateUser("admin");
                        syAjxxMapper.insert(syAjxx);
                    }
                } else {
                    syAjxx.setId(IdUtil.simpleUUID());
                    syAjxx.setUpdateTime(new Date());
                    syAjxx.setUpdateUser("admin");
                    syAjxx.setCreateUser("admin");
                    syAjxxMapper.insert(syAjxx);
                }

            }
        }
    }
}
